define(function (require, exports, module) {
    var angular = require('angular');
    require("angular-ui");
    
    require('/static_public/js/angular_directive/location');
    
    var env = require('environment');
    var util = require('util');
    require("angular-interceptor");
    
    angular.module('app', ['ngUI','ngInterceptor','locationSelector'])
        .constant('api.path.activity', "/api/index.php?r=xmf/xmf-activity/")
        .factory('ActivityService', [
            '$http',
            'api.path.activity',
            function ($http, api_path) {
                var httpClient = {
                    get: function (api, data) {
                        var url = api_path + api;
                        var search = (data && data.search) || {};
                        angular.forEach(search, function (val, key) {
                            url += "&" + key + "=" + val;
                        });

                        return $http.get(url)
                            .then(function (res) {
                                if (res.retCode === "0") {
                                    return res;
                                }
                            })
                    },
                    post: function (api, data) {
                        return $http.post(api_path + api, (data && data.data) || {})
                            .then(function (res) {
                                res = res.data;
                                if (res.retCode === "0") {
                                    return res;
                                }
                            })
                    }
                }
                return {
                    getActivityInfo: function (data) {
                        return httpClient.post('edit-activity', data)
                    },
                    getInitActivityInfo: function (data) {
                        return httpClient.post('new-activity', data)
                    },
                    createActivity : function (data) {
                        return httpClient.post('add-activity', data)
                    },
                    updateActivity : function (data) {
                        return httpClient.post('update-activity', data)
                    },
                    deleteTask : function (data) {
                        return httpClient.post('del-task', data)
                    },
                    getImgId : function(data) {
                        return httpClient.post('get-img-id', data)                        
                    }
                }
            }
        ])
        .controller('MainController', [
            '$scope',
            '$rootScope',
            '$window',
            'ActivityService',
            function ($scope, $rootScope, $window,service) {
                
                
                $scope.getActivityInfo = function(id){
                    service.getActivityInfo({
                        data: {
                            act_id: id,
                            proj_id: util.getUrlPara('pid')
                        }
                    })
                        .then(function(res){
                            $scope.activity = res.data;
                                        
                            $scope.detail = $scope.activity.act_detail;
                            $scope.activity_type_id = $scope.activity.act_detail.act_type_id;
                            $scope.activity_token = $scope.activity.act_detail.mtoken;
                        })
                };   
                
                $scope.createActivity = function(data){
                    service.createActivity({
                        data: data
                    })
                        .then(function(res){
                            $rootScope.$emit('success','保存成功');
                            setTimeout(function(){
                                $scope.cancel();
                            },1000)
                        })
                };
                
                $scope.updateActivity = function(data) {
                    service.updateActivity({
                        data: data
                    })
                        .then(function(res){
                            $rootScope.$emit('success','编辑成功');
                            setTimeout(function(){
                                $scope.cancel();
                            },1000)
                        })
                };
                
                $scope.taskViewer = {
                    init: function(scope,data){
                        var users = [];
                        
                        if ($scope.activity && $scope.activity.users) {
                            angular.forEach($scope.activity.users,function(user){
                                users.push(angular.extend({},user,{checked:false}))
                            });
                        }
                        
                        scope.users = users;
                        
                        data.member_users = data.member_users || [];
                        
                        var detail = ($scope.activity && $scope.activity.act_detail) || {};
                        if (!data.t_activity_taskId || !data.is_create) {
                           angular.extend(data,{
                                start_time: detail.start_time,
                                end_time: detail.end_time,
                                province: detail.province,
                                province_name: detail.province_name,
                                city: detail.city,
                                city_name: detail.city_name,
                                district: detail.district,
                                district_name: detail.district_name,
                                is_create: true
                            });
                        }
                        
                        scope.checker = {
                            all: false,
                            checkAll: function () {
                                var all = scope.checker.all;
                                for (var i = 0; i < scope.users.length; i++) {
                                    var user = scope.users[i];
                                    user.checked = all;
                                    
                                    user.id = user.id || user.user_id;
                                    var selected = false;
                                    for(var j = 0; j < data.member_users.length;j++) {
                                        if (data.member_users[j].user_id === user.user_id || data.member_users[j].id === user.user_id) {
                                            selected = true;
                                            if (!all) {
                                                data.member_users.splice(j,1);
                                            }
                                            break;
                                        } 
                                    }
                                    
                                    if (!selected && all) {
                                        data.member_users.push(user);
                                    }
                                }
                            },
                            check: function (user) {
                                var all = true;
        
                                for (var i = 0; i < scope.users.length; i++) {
                                    if (!scope.users[i].checked) {
                                        all = false;
                                    }
                                }
                                
                                var selected = false;
                                for(var j = 0; j < data.member_users.length;j++) {
                                    user.id = user.id || user.user_id;
                                    if (data.member_users[j].user_id === user.user_id || data.member_users[j].id === user.user_id) {
                                        selected = true;
                                        if (!user.checked) {
                                            data.member_users.splice(j,1);
                                        }
                                        break;
                                    }
                                }
                                
                                if (!selected && user.checked) {
                                    data.member_users.push(user);
                                }
                                
                                scope.checker.all = all;
                            }
                        };
                        
                        scope.deselectUser = function(user) {
                            user.user_id = user.user_id || user.id;
                            for(var j = 0; j < data.member_users.length;j++) {
                                if (data.member_users[j].user_id === user.user_id || data.member_users[j].id === user.user_id) {
                                    data.member_users.splice(j,1);
                                    break;
                                }
                            }
                            
                            for (var i = 0; i < scope.users.length; i++) {
                                if (scope.users[i].user_id === user.user_id) {
                                    scope.users[i].checked = false;
                                    break;
                                }
                            }
                            
                            scope.checker.all = false;
                        };
                        
                        scope.userFilter = function(user){
                            for (var i = 0; i < data.member_users.length; i++) {
                                var member = data.member_users[i];
                                if (member.user_id === user.user_id || member.id === user.user_id) {
                                    return false;
                                }
                            }
                            var keyword = scope.keyword || "";
                            return user.user_name.indexOf(keyword) > -1 || user.mobile.indexOf(keyword) > -1
                        };
                    },
                    save: function(scope,dialog,data,index){
                        
                        if (!data.start_time) {
                            $rootScope.$emit('error','请设置活动开始时间',true);
                            return false;
                        } 
                        
                        if (!data.end_time) {
                            $rootScope.$emit('error','请设置活动结束时间',true);
                            return false;
                        }
                        
                        if (!data.target || !/^\d+$/.test(data.target)) {
                            $rootScope.$emit('error','请填写正确的拓客目标',true);
                            return false;
                        }
                        
                        if (!data.province || !data.city || !data.district) {
                            $rootScope.$emit('error','请设置活动地点',true);
                            return false;
                        }
                        
                        if (!data.address) {
                            $rootScope.$emit('error','请设置活动街道/单位',true);
                            return false;
                        }
                        
                        var members = [];
                        
                        angular.forEach(data.member_users,function(user){
                            members.push(user.user_name);
                        });
                        
                        data.members = members.join('、');
                        
                        if (index !== undefined) {
                            $scope.activity.task_detail[index] = data;
                        } else {
                            $scope.activity.task_detail = $scope.activity.task_detail || [];
                            $scope.activity.task_detail.push(data);
                        }
                    }    
                };
                
                $scope.deleteTask = function(task,index){
                    if (task.t_activity_taskId) {
                        service.deleteTask({
                            data: {
                                task_id: task.t_activity_taskId
                            }
                        })
                            .then(function(res){
                                $scope.activity.task_detail.splice(index,1);
                                $scope.del_tasks = $scope.del_tasks || [];
                                $scope.del_tasks.push(task.t_activity_taskId)
                            })
                    } else {
                        $scope.activity.task_detail.splice(index,1);
                    }
                };
                
                $scope.setImgInfo = function(){
                    service.getImgId({
                        data: {
                            mtoken: $scope.activity_token
                        }
                    })
                        .then(function(res){
                            $window.location.href = "http://www.myscrm.cn/index.php?g=User&m=Img&a=edit&id=" + res.data;
                        })
                };
                
                $scope.$watch('activity_token',function(token){
                    if (token) {
                        service.getImgId({
                            data: {
                                mtoken: $scope.activity_token
                            }
                        })
                            .then(function(res){
                                $scope.setImgInfoUrl = env.pigcms + "/index.php?g=User&m=XmfImg&a=edit&id=" + res.data + "&accessKey=" + $scope.activity.act_detail.access_key;
                            })
                    }
                });
                
                $scope.save = function(){
                    var detail = $scope.activity.act_detail;
                    
                    angular.extend(detail,{         
                        mtoken: $scope.activity_token,
                        act_type_id: $scope.activity_type_id
                    });
                    
                    if (!detail.act_name) {
                        $rootScope.$emit('error','请设置活动名称',true);
                        return false;
                    } 
                    
                    if (!detail.act_type_id && !$scope.activity.act_type_list.length) {
                        $rootScope.$emit('error','活动类型不能为空，请去参数设置中启用类型',true);
                        return false;
                    }
                    
                    if (!detail.start_time) {
                        $rootScope.$emit('error','请设置活动开始时间',true);
                        return false;
                    } 
                    
                    if (!detail.end_time) {
                        $rootScope.$emit('error','请设置活动结束时间',true);
                        return false;
                    }
                    
                    if (detail.target && !/^\d+$/.test(detail.target)) {
                        $rootScope.$emit('error','请填写正确的拓客目标',true);
                        return false;
                    }
                    
                    if (!detail.province || !detail.city || !detail.district) {
                        $rootScope.$emit('error','请设置活动地点',true);
                        return false;
                    }
                    
                    if (!detail.address) {
                        $rootScope.$emit('error','请设置活动街道/单位',true);
                        return false;
                    }
                    
                    if (!$scope.activity.task_detail || !$scope.activity.task_detail.length) {
                        $rootScope.$emit('error','活动必须有一条任务',true);
                        return false;
                    }
                    
                    if (detail.is_reg_agent == 1 && !detail.public_number_url) {
                        $rootScope.$emit('error','请设置跳转公众号URL链接',true);
                        return false;
                    }
                    
                    var api = $scope.activityId ? $scope.updateActivity : $scope.createActivity; 
                    
                    var act_detail = $scope.activity.act_detail;
                    
                    var act_data = {
                        "act_name": act_detail.act_name,
                        "act_type_id": act_detail.act_type_id,
                        "target": act_detail.target,
                        "start_time": act_detail.start_time,
                        "end_time": act_detail.end_time,
                        "address": act_detail.address,//街道地址
                        "remark": act_detail.remark,//备注
                        "is_send_present": act_detail.is_send_present,
                        "is_selected_mtoken": act_detail.is_selected_mtoken,//是否要求关注公众号
                        "mtoken": act_detail.mtoken,
                        "is_reg_agent": act_detail.is_reg_agent,//是否注册经纪人
                        "public_number_url": act_detail.public_number_url,//经纪人注册地址
                        "province": act_detail.province,//省代码
                        "city": act_detail.city,//市
                        "district": act_detail.district,//区
                    };
                    
                    if (act_detail.t_activityId) {
                        angular.extend(act_data,{
                            t_activityId: act_detail.t_activityId
                        });
                    }
                    
                    var task_data = [];
                    
                    var count = 0;
                    
                    angular.forEach($scope.activity.task_detail,function(task){
                        var data = {
                            t_activity_taskId: task.t_activity_taskId,
                            "start_time": task.start_time,
                            "end_time": task.end_time,
                            "address": task.address,
                            "target": task.target,
                            "members": task.members,//成员
                            "province": task.province,
                            "city": task.city,
                            "district": task.district,
                            "user_id": task.user_id
                        };    
                         
                        var user_ids = [];
                        
                        angular.forEach(task.member_users,function(user){
                            user_ids.push(user.user_id || user.id);
                        });
                        
                        count += +task.target;
                        
                        data.user_id = user_ids;
                        
                        task_data.push(data);
                    });
                    
                    act_data.target = $scope.activity.act_detail.target = count;
                    
                    var data = {
                        proj_id: util.getUrlPara('pid'),
                        act_data: act_data,
                        task_data: task_data
                    };
                    
                    if ($scope.activityId) {
                        angular.extend(data,{
                            del_task: $scope.del_tasks || []
                        })
                    }
                    
                    api(data);
                };
                
                $scope.activityId = util.getUrlPara("id");
                
                if ($scope.activityId) {
                    $scope.getActivityInfo($scope.activityId);
                } else {
                    service.getInitActivityInfo({
                        data: {
                            proj_id: util.getUrlPara('pid')
                        }
                    })
                        .then(function(res) {
                            $scope.activity = res.data;
                                        
                            $scope.detail = $scope.activity.act_detail;
                            
                            for(var i = 0; i < $scope.activity.act_type_list.length; i++) {
                                if ($scope.activity.act_type_list[i].is_default == 1) {
                                    $scope.activity_type_id = $scope.activity.act_type_list[i].type_id;
                                    break;
                                }
                            }
                            try {
                                if (!$scope.activity_type_id) {
                                    $scope.activity_type_id = $scope.activity.act_type_list[0].type_id;
                                }
                                $scope.activity_token = $scope.activity.token_list[0].token;                           
                            } catch (err) {
                                
                            }
                        })
                }
                
                $scope.cancel = function(){
                    $window.location.href = "/page/intermediary_organ/bee/index.shtml?token=" + util.getUrlPara('token') + "#/activity"
                };
            }
        ])
    
    angular.bootstrap(document, ['app']);
});
